import 'package:flutter/material.dart';
import 'package:novel_reader/api/fish_hawk_api.dart';
import 'package:novel_reader/model/book.dart';
import 'package:novel_reader/model/chapter.dart';
import 'package:novel_reader/utils/hive_storage.dart';
import 'package:novel_reader/utils/utils.dart';

class ReaderOperation {
  final State _state;

  ReaderOperation(this._state);

  void loadingTask(Function task) {
    showDialog(
      context: _state.context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text(
              '加载中...',
              style: TextStyle(color: Colors.orange, fontSize: 38),
            ),
          ],
        ),
      ),
    );
    Future(() async {
      try {
        await task();
      } catch (e) {
        debugPrint('loadingTask error:$e');
      }
      if (_state.mounted) {
        Navigator.of(_state.context).pop();
      }
    });
  }

  void updateChapters(Book? book, Function cb) {
    if (book == null) return;
    loadingTask(() async {
      await FishHawkApi.initBook(book);
      cb();
    });
  }

  void updateChapter(Chapter? chapter, Function cb) {
    if (chapter == null) return;
    loadingTask(() async {
      await FishHawkApi.initChapter(chapter);
      cb();
    });
  }

  void showAddBook(List<Book> books) {
    Utils.showInputDialog(_state.context, "请输入书籍码", (String code) {
      addBook(books, code, () => Utils.showToast(_state.context, '添加书籍成功'));
    });
  }

  void addBook(List<Book>? books, String? code, Function? cb) {
    if (null == code || code.length < 3 || books == null) {
      return;
    }
    if (code.endsWith('/')) {
      code = code.substring(0, code.length - 1);
    }
    final Book book = Book(code: code);
    loadingTask(() async {
      if (HiveStorage.getBookByCode(book.code) != null) {
        return;
      }
      await FishHawkApi.initBook(book);
      books.add(book);
      await HiveStorage.saveBook(book);
      if (null != cb) {
        cb();
      }
    });
  }

  void removeBook(Book book, List<Book> books, Function cb) {
    loadingTask(() async {
      await HiveStorage.deleteBook(book.code);
      books.remove(book);
      if (_state.mounted) {
        Utils.showToast(_state.context, '删除成功');
        cb();
      }
    });
  }
}
